package com.spring.shiro.service;

import com.spring.shiro.entity.Dict;
import com.spring.shiro.mapper.DictMapper;
import com.spring.shiro.qo.QueryRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Slf4j
@Service
public class DictService {

    @Autowired
    private DictMapper dictMapper;

    public Dict findById(Long dictId) {
        return this.dictMapper.selectByPrimaryKey(dictId);
    }

    public List<Dict> findAllDicts(Dict dict, QueryRequest request) {
        try {
            Example example = new Example(Dict.class);
            Example.Criteria criteria = example.createCriteria();
            if (StringUtils.isNotBlank(dict.getKeyy())) {
                criteria.andCondition("keyy=", Long.valueOf(dict.getKeyy()));
            }
            if (StringUtils.isNotBlank(dict.getValuee())) {
                criteria.andCondition("valuee=", dict.getValuee());
            }
            if (StringUtils.isNotBlank(dict.getTableName())) {
                criteria.andCondition("table_name=", dict.getTableName());
            }
            if (StringUtils.isNotBlank(dict.getFieldName())) {
                criteria.andCondition("field_name=", dict.getFieldName());
            }
            example.setOrderByClause("TABLE_NAME");
            return this.dictMapper.selectByExample(example);
        } catch (Exception e) {
            log.error("获取字典信息失败", e);
            return new ArrayList<>();
        }
    }

    @Transactional
    public void addDict(Dict dict) {
        this.dictMapper.insert(dict);
    }

    @Transactional
    public void deleteDicts(String dictIds) {
        List<String> list = Arrays.asList(dictIds.split(","));
        Example example = new Example(Dict.class);
        example.createCriteria().andIn("dictId", list);

        this.dictMapper.deleteByExample(example);
    }

    @Transactional
    public void updateDict(Dict dict) {
        this.dictMapper.updateByPrimaryKeySelective(dict);
    }

}
